package cn.hg.jboot.core.validator;

import com.jfinal.kit.Kv;
import com.jfinal.validate.ValidateException;
import com.jfinal.validate.Validator;

import cn.hg.jboot.core.constant.BaseConstants;
import cn.hg.jboot.core.controller.BaseController;
import cn.hutool.core.lang.RegexPool;

/**
 * @author Golly
 */
public abstract class BaseValidator extends Validator {

    protected static final String filePattern = "[\\\\\\\\/:*?\\\"<>|]";
    protected static final String mobilePhonePattern = RegexPool.MOBILE;
    protected static final String telePhonePattern = RegexPool.TEL;

    /*
     * (non-Javadoc)
     * @see com.jfinal.validate.Validator#addError(java.lang.String,
     * java.lang.String)
     */
    @Override
    protected void addError (String errorKey, String errorMessage) {
        this.invalid = true;

        // 重载原方法，如果调用方式为Ajax，则返回Json格式的错误信息
        if (this.controller instanceof BaseController) {
            BaseController bc = (BaseController) this.controller;

            if (bc.isAjaxRequest()) {
                bc.renderAjaxFailed(BaseConstants.RETURN_CODE_VALUE_FAILED, errorMessage, Kv.by("field", errorKey));
            } else {
                this.controller.setAttr(errorKey, errorMessage);
            }

            throw new ValidateException();
        } else {
            this.controller.setAttr(errorKey, errorMessage);

            if (this.shortCircuit) {
                throw new ValidateException();
            }

        }

    }

    /**
     * Validate tele phone.
     */
    protected void validateFileName (String field, String errorKey, String errorMessage) {
        this.validateRegex(field, BaseValidator.filePattern, false, errorKey, errorMessage);
    }

    /**
     * Validate mobile phone.
     */
    protected void validateMobilePhone (String field, String errorKey, String errorMessage) {

        this.validateRegex(field, BaseValidator.mobilePhonePattern, false, errorKey, errorMessage);
    }

    /**
     * Validate tele phone.
     */
    protected void validateTelePhone (String field, String errorKey, String errorMessage) {
        this.validateRegex(field, BaseValidator.telePhonePattern, false, errorKey, errorMessage);
    }

}
